package com.longqinuo.mycarservice.fragments;

import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.longqinuo.mycarservice.R;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AddCarFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AddCarFragment extends Fragment implements View.OnClickListener {

    private ImageView mBack;
    private TextView mTitle;
    private ImageView mEdit;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private List<String> typeList;
    private String types[] = {"小型汽车","重型卡车","摩托车","三轮车","面包车","商务车"};
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Toast toast;
    private String mProvince; //输入的省份
    private String carNumber;  //车牌号
    private String carCode;   //车辆识别代号

    private TextView mSmallCar;
    private OnFragmentInteractionListener mListener;
    private ImageView iv_car_type_show;
    private ImageView mNext;
    private Spinner spin_car_province;
    private EditText et_car_number_add;
    private EditText et_car_code_add;
    private ImageView iv_car_code_show;
    private Button btn_start_query_add;


    public AddCarFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AddCarFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AddCarFragment newInstance(String param1, String param2) {
        AddCarFragment fragment = new AddCarFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_car, container, false);
        initData();
        initView(view);
        return view;
    }

    private void initData() {
        typeList = new ArrayList<>();
        for (int i = 0; i < types.length; i++) {
            typeList.add(types[i]);
        }
    }

    private void initView(View view) {
        manager = getActivity().getSupportFragmentManager();
        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mEdit = (ImageView) view.findViewById(R.id.iv_top_option);
        mNext = (ImageView) view.findViewById(R.id.iv_next_car_type);
        mSmallCar = (TextView) view.findViewById(R.id.tv_small_car_type);
        mSmallCar.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mBack.setOnClickListener(this);
        mTitle.setText("添加车辆");
        mEdit.setVisibility(View.INVISIBLE);
        iv_car_type_show = (ImageView) view.findViewById(R.id.iv_car_type_show);
        iv_car_type_show.setOnClickListener(this);
        spin_car_province = (Spinner) view.findViewById(R.id.spin_car_province);
        final String provinces[] = getActivity().getResources().getStringArray(R.array.province);
        spin_car_province.setAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_spinner_item,provinces));
        spin_car_province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mProvince = provinces[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        et_car_number_add = (EditText) view.findViewById(R.id.et_car_number_add);
        et_car_code_add = (EditText) view.findViewById(R.id.et_car_code_add);
        iv_car_code_show = (ImageView) view.findViewById(R.id.iv_car_code_show);
        iv_car_code_show.setOnClickListener(this);
        btn_start_query_add = (Button) view.findViewById(R.id.btn_start_query_add);
        btn_start_query_add.setOnClickListener(this);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        mTransaction = manager.beginTransaction();
        switch (v.getId()) {
            case R.id.iv_top_back:
                manager.popBackStack();
                break;
            case R.id.iv_car_type_show:
                toast = new Toast(getActivity());
                View typeView = View.inflate(getActivity(),R.layout.my_type_picture_toast,null);
                toast.setView(typeView);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.show();
                break;
            case R.id.tv_small_car_type:
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle(R.string.place_selected_car_type);
                builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_checked, typeList), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mSmallCar.setText(types[which]);
                    }
                });
                builder.create().show();
                break;

            case R.id.iv_car_code_show:
                toast = new Toast(getActivity());
                View codeView = View.inflate(getActivity(),R.layout.my_code_picture_toast,null);
                toast.setView(codeView);
                toast.setGravity(Gravity.CENTER,0,0);
                toast.show();
                break;
            case R.id.btn_start_query_add:
                if (submit()) {

                    mTransaction = manager.beginTransaction();
                    mTransaction.replace(R.id.ll_main_layout,BreakResultFragment.newInstance(mProvince+carNumber,""),"BreakResult");
                    mTransaction.addToBackStack("BreakResult");
                    mTransaction.commit();

                }
                break;
            case R.id.iv_next_car_type:
                mTransaction.replace(R.id.ll_main_layout,new SelectedBrandFragment(),"SelectedBrand");
                mTransaction.addToBackStack("SelectedBrand");
                mTransaction.commit();
                break;
            default:
                break;
        }

    }

    private boolean submit() {
        // validate
        carNumber = et_car_number_add.getText().toString().trim();
        if (TextUtils.isEmpty(carNumber)) {
            Toast.makeText(getContext(), "请输入车牌号", Toast.LENGTH_SHORT).show();
            return false;
        }

        carCode = et_car_code_add.getText().toString().trim();
        if (TextUtils.isEmpty(carCode)) {
            Toast.makeText(getContext(), "请输入车辆识别代号后6位", Toast.LENGTH_SHORT).show();
            return false;
        }

        // TODO validate success, do something

        return  true;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
